package org.meichao.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

/**
 * 定义数据源
 */
@Configuration
public class DataSourceConfig {

    private Logger logger = LoggerFactory.getLogger(DataSourceConfig.class);

    @Value("${spring.datasource.type}")
    private Class<? extends DataSource> dataSourceType;

    /**
     * 配置写库
     * DataSourceBuilder里很几个默认的数据源，
     *  必须得加@Primary来确定优先执行，不然会报数据源找不到
     * @Primary 当几个类都实现继承了同一个类，且都被@Configuration注释,用@Primary来确定优先执行哪个类
     *  和@Qualifier作用差不多，只不过@qualifier是通过name属性决定执行哪个类
     */
    @Bean(name = "writeDataSource",destroyMethod = "close")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.write")
    public DataSource writeDataSource(){
        logger.info("-----------writeDataSource init----------");
        return DataSourceBuilder.create().type(dataSourceType).build();

    }

    /**
     * 配置读库
     *
     */
    @Bean(name = "readDataSource",destroyMethod = "close")
    @ConfigurationProperties(prefix = "spring.datasource.read")
    public DataSource readDataSource(){
        logger.info("-----------readDataSource init----------");
        return DataSourceBuilder.create().type(dataSourceType).build();

    }
}
